// stores/auth.ts
import {defineStore} from 'pinia'
import {fetchLogin} from '@/api/auth/Auth'
import {usePermissionStore} from "@/stores/premission_store.ts";
import {Authorization, REFRESH_TOKEN} from '@/constant'
import {fetchUserRole} from "@/api/role";
import {fetchUserDetails} from "@/api/user";

export const useAuthStore = defineStore('auth', {
  state: () => ({
    // 认证令牌
    accessToken: localStorage.getItem(Authorization) || '',
    refreshToken: localStorage.getItem(REFRESH_TOKEN) || '',
    // 用户基本信息
    userInfo: {} as User.UserDetails | null,
    roles: [] as Role.BaseInfo[] | null,
    // 登录状态
    isLoggedIn: !!localStorage.getItem(Authorization)
  }),

  actions: {
    /**
     * 用户名密码登录
     * @param username 用户名
     * @param password 密码（明文）
     */
    async login(username: string, password: string) {
      try {
        const loginData = await fetchLogin(username, password)

        // 更新存储状态
        this.accessToken = loginData.accessToken
        this.refreshToken = loginData.refreshToken
        this.isLoggedIn = true

        // 持久化存储
        localStorage.setItem(Authorization, loginData.accessToken)
        localStorage.setItem(REFRESH_TOKEN, loginData.refreshToken)

        // 获取并存储用户信息
        await this.getUserInfo()
        // 获取用户角色
        await this.getUserRole()
        return Promise.resolve(loginData)
      } catch (error) {
        this.logout()
        return Promise.reject(error)
      }
    },

    /**
     * 获取用户详细信息
     */
    async getUserInfo() {
      try {
        this.userInfo = await fetchUserDetails(null)
        return this.userInfo
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return Promise.reject(error)
      }
    },
    /**
     * 获取用户详细信息
     */
    async getUserRole() {
      try {
        this.roles = await fetchUserRole()
        return this.roles
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return Promise.reject(error)
      }
    },

    /**
     * 退出登录
     */
    logout() {
      // 清除状态
      this.$reset()
      // 清除本地存储
      localStorage.removeItem(Authorization)
      localStorage.removeItem(REFRESH_TOKEN)
      // 重置权限相关状态
      usePermissionStore().$reset()
      console.log('退出登录')
    }
  }
})
